import { Injectable, Logger } from '@nestjs/common';
// 使用新的 PayPal SDK
import * as paypal from '@paypal/checkout-server-sdk';

@Injectable()
export class PaypalService {
  private readonly logger = new Logger(PaypalService.name);
  private readonly client: any;

  constructor() {
    // 从环境变量获取 PayPal 凭据
    const clientId = process.env.PAYPAL_CLIENT_ID;
    const clientSecret = process.env.PAYPAL_CLIENT_SECRET;

    if (!clientId || !clientSecret) {
      this.logger.error('Missing PayPal credentials in environment variables');
      throw new Error('Missing PayPal credentials');
    }

    // 根据环境设置 PayPal 凭据
    const environment = new paypal.core.SandboxEnvironment(
      clientId,
      clientSecret,
    );
    this.client = new paypal.core.PayPalHttpClient(environment);
  }

  /**
   * 创建 PayPal 订单
   * @param amount 金额
   * @param currency 货币代码
   * @param description 描述
   * @returns 订单 ID
   */
  async createOrder(
    amount: string,
    currency: string = 'USD',
    description: string = '粉钻充值',
  ): Promise<string> {
    this.logger.log(`Creating PayPal order for amount: ${amount} ${currency}`);

    try {
      const request = new paypal.orders.OrdersCreateRequest();
      request.requestBody({
        intent: 'CAPTURE',
        purchase_units: [
          {
            description: description,
            amount: {
              currency_code: currency,
              value: amount,
            },
          },
        ],
        application_context: {
          cancel_url: `${process.env.APP_URL}/paypal/cancel`,
          return_url: `${process.env.APP_URL}/paypal/return`,
        },
      });

      const response = await this.client.execute(request);
      const orderId = response.result.id;
      this.logger.log(`Created PayPal order with ID: ${orderId}`);
      return orderId;
    } catch (error) {
      this.logger.error('Failed to create PayPal order', error);
      throw new Error('Failed to create PayPal order');
    }
  }

  /**
   * 捕获 PayPal 订单
   * @param orderId 订单 ID
   * @returns 捕获结果
   */
  async captureOrder(orderId: string): Promise<any> {
    this.logger.log(`Capturing PayPal order: ${orderId}`);

    try {
      const request = new paypal.orders.OrdersCaptureRequest(orderId);
      const response = await this.client.execute(request);
      this.logger.log(`Successfully captured PayPal order: ${orderId}`);
      return response.result;
    } catch (error) {
      this.logger.error(`Failed to capture PayPal order: ${orderId}`, error);
      throw new Error('Failed to capture PayPal order');
    }
  }
}
